<?php

namespace app\v1\controller;

use app\model\AddressModel;
use support\Request;
use support\Response;
use Exception;

/**
 * 地址管理控制器
 * 
 * 提供用户地址的增删改查功能
 * 
 * @package app\v1\controller
 */
class AddressController
{
    /**
     * 获取用户地址列表
     * 
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            $userId = $user->id;

            // 获取分页参数
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);

            // 查询地址列表
            $addresses = AddressModel::where('user_id', $userId)
                ->orderBy('is_default', 'desc')
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            return json([
                'data' => [
                    'list' => $addresses->items(),
                    'total' => $addresses->total(),
                    'current_page' => $addresses->currentPage(),
                    'per_page' => $addresses->perPage(),
                    'last_page' => $addresses->lastPage()
                ],
                'msg' => '获取地址列表成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取地址详情
     * 
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = $request->get('id');
            if (empty($id)) {
                throw new Exception('地址ID不能为空');
            }

            $userId = $this->getUserIdFromRequest($request);
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            $address = AddressModel::where('id', $id)
                ->where('user_id', $userId)
                ->first();

            if (!$address) {
                throw new Exception('地址不存在');
            }

            return json([
                'data' => $address,
                'msg' => '获取地址详情成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 添加地址
     * 
     * @param Request $request
     * @return Response
     */
    public function add(Request $request): Response
    {
        try {
            $userId = $this->getUserIdFromRequest($request);
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            $name = $request->post('name');
            if (empty($name)) {
                throw new Exception('收货人姓名不能为空');
            }

            $phone = $request->post('phone');
            if (empty($phone)) {
                throw new Exception('收货人电话不能为空');
            }

            $province = $request->post('province');
            if (empty($province)) {
                throw new Exception('省份不能为空');
            }

            $city = $request->post('city');
            if (empty($city)) {
                throw new Exception('城市不能为空');
            }

            $district = $request->post('district');
            if (empty($district)) {
                throw new Exception('区县不能为空');
            }

            $detail = $request->post('detail');
            if (empty($detail)) {
                throw new Exception('详细地址不能为空');
            }

            $isDefault = (int)$request->post('is_default', 0);

            // 如果设置为默认地址，先取消其他默认地址
            if ($isDefault) {
                AddressModel::where('user_id', $userId)
                    ->where('is_default', 1)
                    ->update(['is_default' => 0]);
            }

            // 创建新地址
            $address = new AddressModel();
            $address->user_id = $userId;
            $address->name = $name;
            $address->phone = $phone;
            $address->province = $province;
            $address->city = $city;
            $address->district = $district;
            $address->detail = $detail;
            $address->is_default = $isDefault;
            $address->created_at = time();
            $address->updated_at = time();

            if (!$address->save()) {
                throw new Exception('添加地址失败');
            }

            return json([
                'data' => $address,
                'msg' => '添加地址成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新地址
     * 
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('地址ID不能为空');
            }

            $userId = $this->getUserIdFromRequest($request);
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            // 检查地址是否存在
            $address = AddressModel::where('id', $id)
                ->where('user_id', $userId)
                ->first();

            if (!$address) {
                throw new Exception('地址不存在');
            }

            $name = $request->post('name');
            if (empty($name)) {
                throw new Exception('收货人姓名不能为空');
            }

            $phone = $request->post('phone');
            if (empty($phone)) {
                throw new Exception('收货人电话不能为空');
            }

            $province = $request->post('province');
            if (empty($province)) {
                throw new Exception('省份不能为空');
            }

            $city = $request->post('city');
            if (empty($city)) {
                throw new Exception('城市不能为空');
            }

            $district = $request->post('district');
            if (empty($district)) {
                throw new Exception('区县不能为空');
            }

            $detail = $request->post('detail');
            if (empty($detail)) {
                throw new Exception('详细地址不能为空');
            }

            $isDefault = (int)$request->post('is_default', 0);

            // 如果设置为默认地址，先取消其他默认地址
            if ($isDefault) {
                AddressModel::where('user_id', $userId)
                    ->where('id', '!=', $id)
                    ->where('is_default', 1)
                    ->update(['is_default' => 0]);
            }

            // 更新地址信息
            $address->name = $name;
            $address->phone = $phone;
            $address->province = $province;
            $address->city = $city;
            $address->district = $district;
            $address->detail = $detail;
            $address->is_default = $isDefault;
            $address->updated_at = time();

            if (!$address->save()) {
                throw new Exception('更新地址失败');
            }

            return json([
                'data' => $address,
                'msg' => '更新地址成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除地址
     * 
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('地址ID不能为空');
            }

            $userId = $this->getUserIdFromRequest($request);
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            // 检查地址是否存在
            $address = AddressModel::where('id', $id)
                ->where('user_id', $userId)
                ->first();

            if (!$address) {
                throw new Exception('地址不存在');
            }

            // 删除地址
            if (!$address->delete()) {
                throw new Exception('删除地址失败');
            }

            return json([
                'data' => null,
                'msg' => '删除地址成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 设置默认地址
     * 
     * @param Request $request
     * @return Response
     */
    public function setDefault(Request $request): Response
    {
        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new Exception('地址ID不能为空');
            }

            $userId = $this->getUserIdFromRequest($request);
            if (empty($userId)) {
                throw new Exception('用户ID不能为空');
            }

            // 检查地址是否存在
            $address = AddressModel::where('id', $id)
                ->where('user_id', $userId)
                ->first();

            if (!$address) {
                throw new Exception('地址不存在');
            }

            // 先取消其他默认地址
            AddressModel::where('user_id', $userId)
                ->where('id', '!=', $id)
                ->where('is_default', 1)
                ->update(['is_default' => 0]);

            // 设置当前地址为默认
            $address->is_default = 1;
            $address->updated_at = time();

            if (!$address->save()) {
                throw new Exception('设置默认地址失败');
            }

            return json([
                'data' => $address,
                'msg' => '设置默认地址成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 从请求中获取用户ID
     * 这里需要根据实际的认证方式来实现
     * 
     * @param Request $request
     * @return int|null
     */
    private function getUserIdFromRequest(Request $request): ?int
    {
        $user = $request->userLogin;
        return $user->id;
    }
} 